/**
 * de.herberlin.sudoku.gui.SimpleSwingPlayground
 */
package de.herberlin.sudoku.gui;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import de.herberlin.sudoku.Field;
import de.herberlin.sudoku.Group;
import de.herberlin.sudoku.Sudoku;
import de.herberlin.sudoku.timer.AnimationEvent;

/**
 * @author herberlin
 * @created 04.06.2006
 */
public class SimpleSwingPlayground extends JPanel implements Printable {

	private Sudoku sudoku = null;

	private ImageIcon backgroundImage = null;

	public SimpleSwingPlayground(Sudoku sudoku) {

		this.setLayout(new BorderLayout());
		this.sudoku = sudoku;
		init();
	}

	public void paint(Graphics g) {

		if (printing) {
			paintChildren(g);
		} else {

			if (backgroundImage == null) {
				super.paint(g);
			} else {
				g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(),
						getHeight(), this);
				paintChildren(g);
			}
		}

	}

	private JPanel createSudokuPanel() {

		DesignFactory design = DesignFactory.getInstance();

		if (design.getBackgroundImage() != null) {
			backgroundImage = new ImageIcon(getClass().getResource(
					"/gfx/" + design.getBackgroundImage()));
		} else {
			backgroundImage = null;
		}

		JPanel panel = new JPanel();
		panel.setOpaque(!design.isTransparent());

		panel
				.setLayout(new GridLayout(this.sudoku.getRadix(), this.sudoku
						.getRadix(), design.getGroupSpacing(), design
						.getGroupSpacing()));
		Group[] groups = sudoku.getSquares();
		for (int i = 0; i < groups.length; i++) {
			panel.add(createSubpanel(groups[i].getFields(), this.sudoku
					.getRadix()));
		}
		return panel;
	}

	private JPanel createSubpanel(Field[] fields, int radix) {

		JPanel p = new JPanel();
		p.setOpaque(!DesignFactory.getInstance().isTransparent());

		p.setLayout(new GridLayout(radix, radix));
		for (int i = 0; i < fields.length; i++) {
			ButtonField button = (ButtonField) fields[i];
			p.add(button);
			button.time(new AnimationEvent());
		}
		return p;
	}

	public void init() {
		removeAll();
		this.add(createSudokuPanel(), BorderLayout.CENTER);
	}

	private boolean printing = false;

	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
			throws PrinterException {
		if (pageIndex > 0)
			return Printable.NO_SUCH_PAGE;

		printing = true;
		graphics.translate((int) pageFormat.getImageableX(), (int) pageFormat
				.getImageableY());
		print(graphics);
		printing = false;

		return Printable.PAGE_EXISTS;
	}
}
